package com.unlcn.ils.sales.backend.service;

import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import cn.huiyunche.commons.utils.QiniuUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.unlcn.ils.sales.backend.bo.*;
import com.unlcn.ils.sales.backend.constant.AutoConfConstant;
import com.unlcn.ils.sales.backend.enums.AttachAuditStatusEnum;
import com.unlcn.ils.sales.backend.enums.OrderPayStatusEnum;
import com.unlcn.ils.sales.backend.enums.OrderStatusEnum;
import com.unlcn.ils.sales.backend.util.UniquenessUtil;
import com.unlcn.ils.sales.base.mapper.SaleOrderMapper;
import com.unlcn.ils.sales.base.mapper.SaleOrderTicketMapper;
import com.unlcn.ils.sales.base.mapper.SaleOrderViewMapper;
import com.unlcn.ils.sales.base.model.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by houjianhui on 2017/5/26.
 */
@Service
public class OrderServiceImpl implements OrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);

    private static final String PRIMARY = "元", KM = "公里";

    @Autowired
    private SaleOrderMapper orderMapper;

    @Autowired
    private OrderAddrService orderAddrService;

    @Autowired
    private OrderSkuService orderSkuService;

    @Autowired
    private SaleOrderViewMapper orderViewMapper;

    @Autowired
    private OrderAuditService orderAuditService;

    @Autowired
    private UserService userService;

    @Autowired
    private AutoConfConstant autoConfConstant;

    @Autowired
    private SaleOrderTicketMapper ticketMapper;

    @Override
    public int save(OrderBO bo, BindingResult br) throws Exception {
        LOGGER.info("OrderServiceImpl.save params OrderBO: {}", bo);
        if (Objects.equals(bo, null) || Objects.equals(bo, "")) {
            LOGGER.info("OrderServiceImpl.save params OrderBO must not be null");
            throw new IllegalArgumentException("销售订单信息不能为空");
        }
        UserViewBO user = userService.getCurrentUser();
        bo.setUserId(user.getId());

        // 校验数据
        verification(bo);

        // 生成订单编码
        bo.setCode(UniquenessUtil.generateUniquenessFlag("CO"));
        // 设置订单状态
        bo.setOrderStatus(OrderStatusEnum.ORDER_INIT.getValue());
        // 保存订单信息
        SaleOrder order = new SaleOrder();
        BeanUtils.copyProperties(bo, order);
        if (bo.getIsPick() ==1){ order.setIsPick(true); }else if(bo.getIsPick() ==0){ order.setIsPick(false); }
        if (bo.getIsTicket() ==1){ order.setIsTicket(true); }else if(bo.getIsTicket() ==0){ order.setIsTicket(false); }
        if (bo.getIsDeliv() ==1){ order.setIsDeliv(true); }else if(bo.getIsDeliv() ==0){ order.setIsDeliv(false); }

        try {
            orderMapper.insertSelective(order);
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl.save error: {}", e);
            throw new BusinessException("保存销售订单信息异常");
        }

        Integer saleOrderId = order.getId();

        // 保存销售订单地址信息
        orderAddrService.save(bo, saleOrderId);

        // 保存销售订单商品车信息
        orderSkuService.save(bo.getOrderSkuBOS(), saleOrderId);

        // 保存销售订单审核信息
        orderAuditService.save(saleOrderId, order.getCode());

        // 保存发票信息
        if (bo.getIsTicket() == 1){
            SaleOrderTicket ticket = new SaleOrderTicket();
            ticket.setOrderId(saleOrderId);
            ticket.setName(bo.getCompanyName());
            ticket.setIdentifyNumber(bo.getIdentifyNumber());
            ticketMapper.insertSelective(ticket);
        }
        return order.getId();
    }

    @Override
    public Integer updateOrderStatusByOrderCode(String orderCode, Integer orderStatus) throws Exception {
        LOGGER.info("OrderServiceImpl.updateOrderStatusByOrderCode params orderCode:{}, orderStatus: {}", orderCode, orderStatus);
        if (StringUtils.isBlank(orderCode)) {
            LOGGER.info("OrderServiceImpl.updateOrderStatusByOrderCode param orderCode must not be null");
            throw new IllegalArgumentException("销售订单编号不能为空");
        } else if (Objects.equals(orderStatus, null) || Objects.equals(orderStatus, "") || Objects.equals(orderStatus, 0)) {
            LOGGER.info("OrderServiceImpl.updateOrderStatusByOrderCode param orderStatus must not be null");
            throw new IllegalArgumentException("销售订单物流状态不能为空");
        }

        // 构建查询条件
        SaleOrderExample example = new SaleOrderExample();
        example.createCriteria().andCodeEqualTo(orderCode);
        // 查询销售订单
        List<SaleOrder> orders = orderMapper.selectByExample(example);
        // 判断销售订单是否存在
        if (CollectionUtils.isEmpty(orders)) {
            LOGGER.info("OrderServiceImpl.updateOrderStatusByOrderCode Current order: {} doesn't exist", orderCode);
            throw new BusinessException("当前销售订单不存在");
        }
        // 获取销售订单
        SaleOrder order = orders.get(0);

        // 验证状态是否合法
        if (Objects.equals(OrderStatusEnum.getByValue(orderStatus), null)){
            LOGGER.info("Sales order status is not legal: {}", orderStatus);
            throw new BusinessException("销售订单状态不合法");
        }

        // 设置销售订单状态
        order.setOrderStatus(orderStatus);
        try {
            return orderMapper.updateByPrimaryKeySelective(order);
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl.updateOrderStatusByOrderCode error: {}", e);
            throw new BusinessException("更新销售订单状态异常");
        }
    }

    @Override
    public Integer updateOrderStatusAndPayStatusByOrderCode(String orderCode, Integer orderStatus, Integer payStatus) throws Exception {
        LOGGER.info("OrderServiceImpl.updateOrderStatusAndPayStatusByOrderCode params orderCode:{}, orderStatus: {}, payStatus: {}", orderCode, orderStatus, payStatus);
        if (StringUtils.isBlank(orderCode)) {
            LOGGER.info("OrderServiceImpl.updateOrderStatusAndPayStatusByOrderCode param orderCode must not be null");
            throw new IllegalArgumentException("销售订单编号不能为空");
        } else if (Objects.equals(orderStatus, null) || Objects.equals(orderStatus, "") || Objects.equals(orderStatus, 0)) {
            LOGGER.info("OrderServiceImpl.updateOrderStatusAndPayStatusByOrderCode param orderStatus must not be null");
            throw new IllegalArgumentException("销售订单物流状态不能为空");
        } else if (Objects.equals(payStatus, null) || Objects.equals(payStatus, "") || Objects.equals(payStatus, 0)) {
            LOGGER.info("OrderServiceImpl.updateOrderStatusAndPayStatusByOrderCode param payStatus must not be null");
            throw new IllegalArgumentException("销售订单支付状态不能为空");
        }

        // 构建查询条件
        SaleOrderExample example = new SaleOrderExample();
        example.createCriteria().andCodeEqualTo(orderCode);
        // 查询销售订单
        List<SaleOrder> orders = orderMapper.selectByExample(example);
        // 判断销售订单是否存在
        if (CollectionUtils.isEmpty(orders)) {
            LOGGER.info("OrderServiceImpl.updateOrderStatusByOrderCode Current order: {} doesn't exist", orderCode);
            throw new BusinessException("当前销售订单不存在");
        }
        // 获取销售订单
        SaleOrder order = orders.get(0);
        // 验证状态是否合法
        if (Objects.equals(OrderStatusEnum.getByValue(orderStatus), null)){
            LOGGER.info("Sales order status is not legal: {}", orderStatus);
            throw new BusinessException("销售订单状态不合法");
        }

        // 设置销售订单状态
        order.setOrderStatus(orderStatus);
        order.setPayStatus(payStatus);
        try {
            return orderMapper.updateByPrimaryKeySelective(order);
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl.updateOrderStatusByOrderCode error: {}", e);
            throw new BusinessException("更新销售订单状态异常");
        }
    }

    @Override
    public Map<String, Object> listSaleOrder(PageVo pageVo, OrderQueryBO queryBO) throws Exception {
        LOGGER.info("OrderServiceImpl.listSaleOrder params OrderQueryBO: {}", queryBO);
        if (Objects.equals(queryBO, null) || Objects.equals(queryBO, "")) {
            LOGGER.info("OrderServiceImpl.listSaleOrder param queryBO must not be null");
            throw new IllegalArgumentException("销售订单查询条件不能为空");
        }
        UserViewBO user = userService.getCurrentUser();

        // 构建查询条件
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("code", queryBO.getCode());
        queryMap.put("userId", user.getId());
        queryMap.put("departRegionCode", queryBO.getDepartRegionCode());
        queryMap.put("destRegionCode", queryBO.getDestRegionCode());
        queryMap.put("orderStatus", queryBO.getOrderStatus());
        queryMap.put("auditStatus", queryBO.getAuditStatus());
        queryMap.put("pickDateBegin", queryBO.getPickDateBegin());
        queryMap.put("pickDateEnd", queryBO.getPickDateEnd());
        queryMap.put("payStatus", queryBO.getPayStatus());
        queryMap.put("attachAuditStatus", queryBO.getAttachAuditStatus());
        return buildListSaleOrder(queryMap, pageVo);
    }

    @Override
    public Map<String, Object> listSaleOrderToPc(PageVo pageVo, OrderQueryBO queryBO) throws Exception {
        LOGGER.info("OrderServiceImpl.listSaleOrderToPc params OrderQueryBO: {}", queryBO);
        // 构建查询条件
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("code", queryBO.getCode());
        queryMap.put("userId", queryBO.getUserId());
        queryMap.put("departRegionCode", queryBO.getDepartRegionCode());
        queryMap.put("destRegionCode", queryBO.getDestRegionCode());
        queryMap.put("orderStatus", queryBO.getOrderStatus());
        queryMap.put("auditStatus", queryBO.getAuditStatus());
        queryMap.put("pickDateBegin", queryBO.getPickDateBegin());
        queryMap.put("pickDateEnd", queryBO.getPickDateEnd());
        queryMap.put("payStatus", queryBO.getPayStatus());
        queryMap.put("attachAuditStatus", queryBO.getAttachAuditStatus());
        return buildListSaleOrder(queryMap, pageVo);
    }

    @Override
    public Integer updateSaleOrderStatusByKyleOrderStatus() throws Exception {
        List<Integer> statusList = new ArrayList<>();
        statusList.add(OrderStatusEnum.ORDER_AWAIT.getValue());
        statusList.add(OrderStatusEnum.ORDER_TOUCH.getValue());
        statusList.add(OrderStatusEnum.ORDER_DELIVERY.getValue());
        SaleOrderExample example = new SaleOrderExample();
        example.createCriteria().andOrderStatusIn(statusList);
        List<SaleOrder> orders = orderMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(orders)) {
            String orderCodes = orders.stream().map(SaleOrder::getCode).collect(Collectors.joining(","));
            List<String> orderLists = getOrderStatusFormKyleResult(orderCodes);
            if (CollectionUtils.isNotEmpty(orderLists)) {
                for (int i = 0; i < orderLists.size(); i++ ) {
                    String[] code_status = orderLists.get(i).split(",");
                    String orderCode = code_status[0];
                    String status = code_status[1];
                    String payStatus = status.split("_")[1];
                    String orderStatus = status.split("_")[0];
                    updateOrderStatusAndPayStatusByOrderCode(orderCode, Integer.valueOf(orderStatus), Integer.valueOf(payStatus));
                }
            }
        }
        return null;
    }

    @Override
    public Integer updateAttachAuditStatusBySaleOrderCode(String orderCode, Integer attachAuditStatus) throws Exception {
        if (StringUtils.isBlank(orderCode)) {
            LOGGER.info("OrderServiceImpl.updateAttachAuditStatusBySaleOrderCode param orderCode must not be null");
            throw new IllegalArgumentException("销售订单编码不能为空");
        } else if (Objects.equals(attachAuditStatus, null) || Objects.equals(attachAuditStatus, "") || Objects.equals(attachAuditStatus, 0)) {
            LOGGER.info("OrderServiceImpl.updateAttachAuditStatusBySaleOrderCode param attachAuditStatus must not be null");
            throw new IllegalArgumentException("销售订单附件审核状态不能为空");
        }
        SaleOrderExample example = new SaleOrderExample();
        example.createCriteria().andCodeEqualTo(orderCode);
        List<SaleOrder> orders  = orderMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(orders)) {
            orders.stream().forEach(item -> {
                item.setAttachAuditStatus(AttachAuditStatusEnum.getByValue(attachAuditStatus).getValue());
                item.setPayStatus(OrderPayStatusEnum.ORDER_TOUCH.getValue());
                orderMapper.updateByPrimaryKeySelective(item);
                // 更新审核表中状态
                //orderAuditService.updateAuditStatusByOrderId(item.getId(), OrderAuditStatusEnum.ORDER_AWAIT.getValue());
            });
        }
        return 0;
    }

    @Override
    public Integer updateAttachAuditStatusBySaleOrderId(Integer id, Integer attachAuditStatus) throws Exception {
        if (Objects.equals(id, null) || Objects.equals(id, "") || Objects.equals(id, 0)) {
            LOGGER.info("OrderServiceImpl.updateAttachAuditStatusBySaleOrderId param id must not be null");
            throw new IllegalArgumentException("销售订单ID不能为空");
        } else if (Objects.equals(attachAuditStatus, null) || Objects.equals(attachAuditStatus, "") || Objects.equals(attachAuditStatus, 0)) {
            LOGGER.info("OrderServiceImpl.updateAttachAuditStatusBySaleOrderId param attachAuditStatus must not be null");
            throw new IllegalArgumentException("销售订单附件审核状态不能为空");
        }
        SaleOrder order = orderMapper.selectByPrimaryKey(id);
        order.setAttachAuditStatus(AttachAuditStatusEnum.getByValue(attachAuditStatus).getValue());
        orderMapper.updateByPrimaryKeySelective(order);
        return 0;
    }

    private Map<String, Object> buildListSaleOrder(Map<String, Object> queryMap, PageVo pageVo) throws Exception {
        String auditStatus = (String) queryMap.get("auditStatus");
        if (StringUtils.isNotBlank(auditStatus)) {
            String[] audit = auditStatus.split(",");
            queryMap.put("audit", audit);
        }

        String idStr = (String) queryMap.get("id");
        if (StringUtils.isNotBlank(idStr)) {
            String[] id = idStr.split(",");
            queryMap.put("ids", id);
        }

        // 统计销售订单记录数
        try {
            pageVo.setTotalRecord(orderViewMapper.countSaleOrder(queryMap));
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl.listSaleOrder TotalRecord error: {}", e);
            throw new BusinessException("统计销售订单纪录数异常");
        }

        // 返回值
        Map<String, Object> map = new HashMap<>();
        if (!Objects.equals(pageVo, null) && !Objects.equals(pageVo, "")) {
            queryMap.put("orderByClause", StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : "so.gmt_create desc");
            queryMap.put("limitStart", pageVo.getStartIndex());
            queryMap.put("limitEnd", pageVo.getPageSize());
            map.put("page", pageVo);
        }
        // 查询销售订单数据
        List<OrderViewBO> orders = Lists.newArrayList();
        try {
            orders = buindSaleOrder(orderViewMapper.listSaleOrder(queryMap));
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl.listSaleOrder error: {}", e);
            throw new BusinessException("查询销售订单信息异常");
        }
        map.put("orderList", orders);
        return map;
    }

    @Override
    public OrderViewBO getSaleOrderByOrderId(Integer orderId) throws Exception {
        LOGGER.info("OrderServiceImpl.getSaleOrderByOrderId param orderId: {}", orderId);
        if (Objects.equals(orderId, null) || Objects.equals(orderId, "") || Objects.equals(orderId, 0)) {
            LOGGER.info("OrderServiceImpl.getSaleOrderByOrderId param orderId must not be null");
            throw new IllegalArgumentException("销售订单ID不能为空");
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("id", orderId);
        try {
            OrderViewDAO dao = orderViewMapper.getSaleOrderDetail(queryMap);
            OrderViewBO bo = new OrderViewBO();
            BeanUtils.copyProperties(dao, bo);
            // SKU
//            List<OrderSkuViewDAO> skuViewDTOS = dao.getOrderSkus();
            List<OrderSkuBO> skuBOS = Lists.newArrayList();
            List<OrderSkuViewDAO> daos = orderViewMapper.listSaleOrderSku(dao.getId());
            if (CollectionUtils.isNotEmpty(daos)) {
                daos.stream().forEach(va -> {
                    OrderSkuBO skuBO = new OrderSkuBO();
                    BeanUtils.copyProperties(va, skuBO);
                    skuBOS.add(skuBO);
                });
            }

            // attach
            List<OrderAttachViewDAO> attachs= dao.getAttachs();
            List<OrderAttachViewBO> attachViewBOS = Lists.newArrayList();

            if (CollectionUtils.isNotEmpty(attachs)) {
                attachs.stream().forEach(item -> {
                    OrderAttachViewBO attachViewBO = new OrderAttachViewBO();
                    BeanUtils.copyProperties(item, attachViewBO);
                    attachViewBO.setUrl(QiniuUtil.generateDownloadURL(item.getPicKey(), ""));
                    attachViewBOS.add(attachViewBO);
                });
            }
            bo.setAttachs(attachViewBOS);
            bo.setOrderSkus(skuBOS);
            return bo;
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl.getSaleOrderByOrderId error: {}", e);
            throw new BusinessException("查询销售订单信息异常");
        }
    }

    /**
     * OrderViewDAO 转换 OrderViewBO
     * @param orders
     * @return
     */
    private List<OrderViewBO> buindSaleOrder(List<OrderViewDAO> orders) {
        if (CollectionUtils.isNotEmpty(orders)) {
            List<OrderViewBO> orderViewBOS = Lists.newArrayList();
            orders.stream().forEach(val -> {
                OrderViewBO bo = new OrderViewBO();
                BeanUtils.copyProperties(val, bo);
                List<OrderSkuViewDAO> skuViewDTOS = val.getOrderSkus();
                List<OrderSkuBO> skuBOS = Lists.newArrayList();
                if (CollectionUtils.isNotEmpty(skuViewDTOS)) {
                    skuViewDTOS.stream().forEach(va -> {
                        OrderSkuBO skuBO = new OrderSkuBO();
                        BeanUtils.copyProperties(va, skuBO);
                        skuBOS.add(skuBO);
                    });
                }
                bo.setOrderSkus(skuBOS);
                bo.setAttachAuditStatusText(AttachAuditStatusEnum.getByValue(bo.getAttachAuditStatus()).getText());
                orderViewBOS.add(bo);
            });
            return orderViewBOS;
        }
        return null;
    }

    @Override
    public OrderPriceBO getOrderPrice(Integer departRegionId, Integer destRegionId, Integer seriesAmt) throws Exception {
        LOGGER.info("OrderServiceImpl.getOrderPrice params departRegionId: {}, destRegionId: {}, seriesAmt: {}", departRegionId, destRegionId, seriesAmt);
        if (Objects.equals(departRegionId, null) || Objects.equals(departRegionId, "") || Objects.equals(departRegionId, 0)) {
            LOGGER.info("OrderServiceImpl.getOrderPrice params departRegionId must not be null");
            throw new IllegalArgumentException("起运地ID不能为空");
        } else if (Objects.equals(destRegionId, null) || Objects.equals(destRegionId, "") || Objects.equals(destRegionId, 0)) {
            LOGGER.info("OrderServiceImpl.getOrderPrice params destRegionId must not be null");
            throw new IllegalArgumentException("目的地ID不能为空");
        } else if (Objects.equals(seriesAmt, null) || Objects.equals(seriesAmt, "") || Objects.equals(seriesAmt, 0)) {
            LOGGER.info("OrderServiceImpl.getOrderPrice params seriesAmt must not be null");
            throw new IllegalArgumentException("商品车数量不能为空");
        }
        List<PriceBO> prices = resolvPriceFormSCResult(departRegionId, destRegionId);
        OrderPriceBO bo = new OrderPriceBO();
        BigDecimal freightPrice = BigDecimal.valueOf(0);
        BigDecimal unitPrice = BigDecimal.valueOf(0);
        BigDecimal standardSalePrice = BigDecimal.valueOf(0);
        BigDecimal dis = BigDecimal.valueOf(0);
        List<FeeBO> fees = new ArrayList<>();
        // 获取整板数量
        Integer brands = autoConfConstant.getBrands();
        if (CollectionUtils.isNotEmpty(prices)) {
            PriceBO priceBO = prices.get(0);
            BeanUtils.copyProperties(priceBO, bo);
            // 计算运费 单台运价*商品车数量
            if (seriesAmt >= brands) {
                freightPrice = priceBO.getTlGrossPrice().multiply(BigDecimal.valueOf(seriesAmt)).setScale(2, BigDecimal.ROUND_HALF_UP);
            } else {
                freightPrice = priceBO.getLtlGrossPrice().multiply(BigDecimal.valueOf(seriesAmt)).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            // 计算保险费
            unitPrice = priceBO.getUnitPrice().multiply(BigDecimal.valueOf(seriesAmt)).setScale(2, BigDecimal.ROUND_HALF_UP);
            // 标准价格
            standardSalePrice = freightPrice.add(unitPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
            dis = priceBO.getMileage();
            bo.setLineId(priceBO.getLineId());
            bo.setInsuranceSalePrice(unitPrice);
            bo.setInsuranceUnitPrice(priceBO.getUnitPrice());
        }
        FeeBO freight = new FeeBO();
        freight.setName("运费");
        freight.setValue(freightPrice + PRIMARY);
        fees.add(freight);
        FeeBO unit = new FeeBO();
        unit.setName("保险费");
        unit.setValue(unitPrice + PRIMARY);
        fees.add(unit);
        FeeBO distance = new FeeBO();
        distance.setName("里程");
        distance.setValue(dis + KM);
        fees.add(distance);
        bo.setStandardSalePrice(standardSalePrice);
        bo.setFeeBOS(fees);
        return bo;
    }

    @Override
    public FreightQueryBO getOrderPrice(Integer departRegionId, Integer destRegionId) throws Exception {
        LOGGER.info("OrderServiceImpl.getOrderPrice params departRegionId: {}, destRegionId: {}", departRegionId, destRegionId);
        if (Objects.equals(departRegionId, null) || Objects.equals(departRegionId, "") || Objects.equals(departRegionId, 0)) {
            LOGGER.info("OrderServiceImpl.getOrderPrice params departRegionId must not be null");
            throw new IllegalArgumentException("起运地ID不能为空");
        } else if (Objects.equals(destRegionId, null) || Objects.equals(destRegionId, "") || Objects.equals(destRegionId, 0)) {
            LOGGER.info("OrderServiceImpl.getOrderPrice params destRegionId must not be null");
            throw new IllegalArgumentException("目的地ID不能为空");
        }

        List<PriceBO> prices = resolvPriceFormSCResult(departRegionId, destRegionId);
        FreightQueryBO bo = new FreightQueryBO();

        BigDecimal distance = BigDecimal.valueOf(0);
        BigDecimal insureFee = BigDecimal.valueOf(0);
        BigDecimal freightUnit = BigDecimal.valueOf(0);
        BigDecimal standardUnit = BigDecimal.valueOf(0);
        BigDecimal freightComplete = BigDecimal.valueOf(0);
        BigDecimal standardComplete = BigDecimal.valueOf(0);
        if (CollectionUtils.isNotEmpty(prices)) {
            PriceBO priceBO = prices.get(0);
            distance = priceBO.getMileage(); //里程
            insureFee = priceBO.getUnitPrice();//保险单价
            //freightUnit = priceBO.getLtlUnitPrice().multiply(distance).setScale(2, BigDecimal.ROUND_HALF_UP);//单公里单台价格
            //standardUnit = priceBO.getTlUnitPrice().multiply(distance).setScale(2, BigDecimal.ROUND_HALF_UP);//单公里整车价格
            standardUnit = priceBO.getLtlGrossPrice();//单台车价格
            standardComplete = priceBO.getTlGrossPrice();//整板车价格
        }
        bo.setDistance(distance);
        bo.setInsureFee(insureFee);
        bo.setFreightUnit(freightUnit);
        bo.setFreightComplete(freightComplete);
        bo.setStandardUnit(standardUnit);
        bo.setStandardComplete(standardComplete);
        return bo;
    }

    /**
     * 调用主数据查询价格
     *
     * @param departRegionId 起始地ID
     * @param destRegionId 目的地ID
     * @return
     * @throws Exception
     */
    private List<PriceBO> resolvPriceFormSCResult(Integer departRegionId, Integer destRegionId) throws Exception {
//        String url = autoConfConstant.getSc() + "/api/price/channel/sale/queryPrice/" + departRegionId + "/" + destRegionId;
        String url = autoConfConstant.getOperation() + "/api/price/querySalePrice/" + departRegionId + "/" + destRegionId;
//        Integer time = autoConfConstant.getScTime();
        Integer time = autoConfConstant.getOperationTime();
        String result = HttpRequestUtil.sendHttpGet(url, null, time);
        if (!Objects.equals(result, null)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msgCode = jsonObject.getString("messageCode");
            String msg = jsonObject.getString("message");
            String data = jsonObject.getString("data");
            Boolean success = jsonObject.getBoolean("success");
            List<PriceBO> bos = JSONArray.parseArray(data, PriceBO.class);
            if (!success) {
                LOGGER.info("OrderServiceImpl resolvPriceFormSCResult result error");
                throw new BusinessException(msgCode, msg);
            }
            return bos;
        }
        return null;
    }

    /**
     * 获取商户端订单状态
     *
     * @return
     * @throws Exception
     */
    private List<String> getOrderStatusFormKyleResult(String orderCode) throws Exception {
        String url = autoConfConstant.getKyle() + "/saleOrder/getOrderStatus";
        Integer time = autoConfConstant.getKyleTime();
        Map<String, Object> map = new HashMap<>();
        map.put("orderCode", orderCode);
        String result = HttpRequestUtil.sendHttpPost(url, map, time);
        if (!Objects.equals(result, null)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String msgCode = jsonObject.getString("messageCode");
            String msg = jsonObject.getString("message");
            String data = jsonObject.getString("data");
            Boolean success = jsonObject.getBoolean("success");
            List<String> orderStr = JSONArray.parseArray(data, String.class);
            if (!success) {
                LOGGER.info("OrderServiceImpl getOrderStatusFormKyleResult result error");
                throw new BusinessException(msgCode, msg);
            }
            return orderStr;
        }
        return null;
    }

    private void verification(OrderBO bo) throws Exception {
        if (Objects.equals(bo.getUserId(), null) || Objects.equals(bo.getUserId(), "")) {
            LOGGER.info("OrderServiceImpl.save params userId must not be null");
            throw new IllegalArgumentException("下单人ID不能为空");
        } else if (Objects.equals(bo.getPickDate(), null)) {
            LOGGER.info("OrderServiceImpl.save params PickDate must not be null");
            throw new IllegalArgumentException("提车时间不能为空");
        } else if (Objects.equals(bo.getBrands(), null) || Objects.equals(bo.getBrands(), "")) {
            LOGGER.info("OrderServiceImpl.save params Brands must not be null");
            throw new IllegalArgumentException("品牌数量不能为空");
        } else if (Objects.equals(bo.getSeriesAmt(), null) || Objects.equals(bo.getSeriesAmt(), "")) {
            LOGGER.info("OrderServiceImpl.save params SeriesAmt must not be null");
            throw new IllegalArgumentException("商品车数量不能为空");
        } else if (Objects.equals(bo.getStandardSalePrice(), null) || Objects.equals(bo.getStandardSalePrice(), "")) {
            LOGGER.info("OrderServiceImpl.save params StandardSalePrice must not be null");
            throw new IllegalArgumentException("标准售价不能为空");
        } else if (Objects.equals(bo.getStandardUnitPrice(), null) || Objects.equals(bo.getStandardUnitPrice(), "")) {
            LOGGER.info("OrderServiceImpl.save params StandardUnitPrice must not be null");
            throw new IllegalArgumentException("标准单公里价格不能为空");
        } else if (Objects.equals(bo.getSuggestSalePrice(), null) || Objects.equals(bo.getSuggestSalePrice(), "")) {
            LOGGER.info("OrderServiceImpl.save params SuggestSalePrice must not be null");
            throw new IllegalArgumentException("销售人员建议价格不能为空");
        }

    }
}
